<template>
  <div class="head-container">
    <el-input v-model="name" class="mb-20px" clearable placeholder="请输入分类名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>
  <div class="head-container">
    <el-tree
      ref="treeRef"
      :data="categoryList"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      default-expand-all
      highlight-current
      node-key="id"
      :show-checkbox="showCheckbox"
      @node-click="handleNodeClick"
      @check="currentChange"
      :default-checked-keys="checkedKeys"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <a @click="openCategoryForm(data)"> 编辑 </a>
            <a style="margin-left: 8px" @click="handleDelete(data)"> 删除 </a>
          </span>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import * as ProductCategoryApi from '@/api/crm/product/category'
import { defaultProps, handleTree } from '@/utils/tree'

defineOptions({ name: 'ProductCategoryTree' })
const props = defineProps({
  showCheckbox: {
    type: Boolean,
    default: () => false
  }
})
// 默认选择的值
const checkedKeys = ref([])
const name = ref('')
const categoryList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()

// 选择事件
const currentChange = (checkNodes, checkedKeys) => {
  emits('currentChange', checkNodes, checkedKeys)
}
// 回显选择的值
const setCheckedKeys = (val) => {
  if (val.length) {
    checkedKeys.value = val
  } else {
    treeRef.value.setCheckedKeys([])
  }
}
/** 获得产品分类树 */
const getTree = async () => {
  const res = await ProductCategoryApi.getProductCategoryList()
  categoryList.value = []
  categoryList.value.push(...handleTree(res))
}

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  emits('node-click', row)
}
const emits = defineEmits(['node-click', 'currentChange'])

/** 添加/修改操作 */
const categoryFormRef = ref()
const openCategoryForm = (type: string, id?: number) => {
  categoryFormRef.value.open(type, id)
}

/** 删除产品分类按钮操作 */
const handleDelete = async (data) => {
  console.log(data)
}

/** 监听deptName */
watch(name, (val) => {
  treeRef.value!.filter(val)
})

/** 初始化 */
onMounted(async () => {
  await getTree()
})
defineExpose({ setCheckedKeys })
</script>
<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
